package com.liming.dao;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import com.liming.item.CartGoodItems;
import com.liming.model.CartGoods;
import com.liming.model.User;
import com.liming.utils.DataSourceUtils;

public class CartGoodsdao {
	
	QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource());
		
	
	
	public int deleteGoods(CartGoods cGoods) {
		
		String sql = "Delete from cart where userid = ? and goodsid = ?";
		Object []params = {cGoods.getUserid(),cGoods.getGoodsid()};
		
		int ans=0;
		try {
			ans=qr.update(sql,params);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return ans;
	}

	public int changeQuantity(CartGoods cGoods) {
		
		String sql = "Update cart set goodsnum = ? where userid = ? and goodsid = ?";
		Object []params = {cGoods.getGoodsnum(),cGoods.getUserid(),cGoods.getGoodsid()};
		
		int ans=0;
		try {
			ans=qr.update(sql,params);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return ans;
		
	}

	
	public List<CartGoods> initializeCart(int userid) {
		List<CartGoods> goods = null;
		String sql = "Select * from cart where userid = ?";
		try {
			goods = qr.query(sql, new BeanListHandler<>(CartGoods.class),userid);
			if (goods.size()==0||goods==null) {
				return null;
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return goods;
	}

	
	public int putInCart(CartGoods cGoods) {
		String sql = "Insert into cart values(?,?,?,?)";
		Object []params = {
				cGoods.getUserid(),
				cGoods.getGoodsid(),
				cGoods.getGoodsnum(),
				cGoods.getGoodsdetial()
		};
		
		int ans=0;
		try {
			ans=qr.update(sql,params);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		System.out.println(ans);
		return ans;
	}

	public List<CartGoodItems> getAllGoods(int userid) {
		
		List<CartGoodItems> goods = null;
		String sql = "SELECT * from cart , goods where cart.goodsid = goods.goodsid && userid = ?";
		try {
			goods = qr.query(sql, new BeanListHandler<>(CartGoodItems.class),userid);
			if (goods.size()==0||goods==null) {
				return null;
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return goods;
	}
}
